import React, {Component, ComponentClass} from 'react';
import Taro from '@tarojs/taro';
import {View, Text, Picker} from '@tarojs/components';
import {AtSwitch, AtInput, AtIcon} from 'taro-ui';
import {connect} from 'react-redux';
import {DateType} from '../../reducers/select-date';
import {
  Address
} from '../../utils/server.interface';
import {http} from '../../utils/http';
import {
  ADDRESS_DEL,
  ADDRESS_DETAIL,
  ADDRESS_ADD,
  ADDRESS_EDIT, ADD_MATCH, REGION_ALL,
} from '../../constants/api';
import {getHeadTop, vcmonitor} from "../../utils/tools";
import {newHttp} from "../../utils/request";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './detail.scss';

type PageStateProps = {
  selectDate: DateType
}

type PageDispatchProps = {}

type PageOwnProps = {}

type PageState = {
  data: Address
  showLoading: boolean
  addressData: any
  title: string
  searchBarTop: number
  api: string
  edit: boolean
  delshow: boolean
  listnum: number
  showNav: boolean
}

type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface DetailWeb {
  props: IProps
}


@connect(({selectDate}) => ({
  selectDate,
}), () => ({}))

class DetailWeb extends Component {
  state: PageState = {
    data: {
      address: '',
      add: '',
      name: '',
      phone: '',
      addary: [],
      default: false
    },
    rangeKey: [0, 0, 0],
    rangeData: [[], [], []],
    formData: {
      province: "",
      city: "",
      country: ""
    },
    edit: false,
    showNav: false,
    listnum: 0,
    delshow: false,
    title: '新增地址',
    api: ADDRESS_ADD,
    searchBarTop: 0,
    showLoading: true,
    addressData: [],
  }

  async UNSAFE_componentWillMount() {
    const id = Taro.getCurrentInstance().router.params.id as string | undefined;
    if (process.env.TARO_ENV === 'h5') {
      const data = await http.carGet(REGION_ALL)
      this.setState({addressData: data}, async () => {
        this.handleCityData([0, 0, 0]);
      })
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    this.setState({searchBarTop})
    if (id) {
      const listnum = Taro.getCurrentInstance().router.params.listnum;
      const data = await http.carGet<Address>(ADDRESS_DETAIL, {id})
      data.default = data.default ? true : false
      this.setState({
        title: '编辑地址',
        api: ADDRESS_EDIT,
        listnum,
        data
      })
      this.handleCityDataStr(data.add);
    } else {
      const wx = Taro.getCurrentInstance().router.params.wx as string | undefined;
      const {data} = this.state
      const that = this
      if (wx) {
        Taro.chooseAddress({
          success(res) {
            data['name'] = res.userName
            data['phone'] = res.telNumber
            data['addary'] = [res.provinceName, res.cityName, res.countyName]
            data['add'] = data.addary.join(',')
            data['address'] = res.detailInfo
            that.setState({data})
          },
          fail(res) {
            Taro.navigateBack({
              delta: 1
            })
          }
        })
      } else {
        if (process.env.TARO_ENV === 'weapp') {
          Taro.getClipboardData({
            success(res) {
              if (res.data) {
                newHttp.post(ADD_MATCH, {address: res.data}).then(r => {
                  r.data
                  data['addAry'] = [r.data.province || '', r.data.city || '', r.data.county || '']
                  data['add'] = data['addAry'].join(',')
                  data['address'] = r.data.town + r.data.village
                  data['phone'] = r.data.phone || ''
                  that.setState({data})
                })
              }
            }
          })
        }

      }
    }
  }

  selectPhoneNumber(str) {
    const regx = /(1[3|4|5|7|8][\d]{9}|0[\d]{2,3}-[\d]{7,8}|400[-]?[\d]{3}[-]?[\d]{4})/g;
    return str.match(regx);
  }

  onPullDownRefresh() {
    Taro.stopPullDownRefresh();
  }

  shareParams = ''

  async componentDidShow() {
    vcmonitor(this)
  }

  async delAdd() {
    const {data} = this.state
    const r = await http.postCar(ADDRESS_DEL, {id: data.id})
    if (r) {
      Taro.navigateBack({
        delta: 1
      })
    } else {
      Taro.showToast({
        title: '删除失败',
        icon: 'none'
      })
    }
  }

  delShow() {
    this.setState({delshow: !this.state.delshow})
  }

  async componentDidHide() {
    this.setState({firstGet: false})
  }

  handleChange() {
    const {data} = this.state
    if (data.id) {
      this.setState({edit: true})
    }
    data['default'] = !data.default
    this.setState({data})
  }

  changeName(e) {
    const {data} = this.state
    if (data.id) {
      this.setState({edit: true})
    }
    data.name = e
    this.setState({data})
  }

  changePhone(e) {
    const {data} = this.state
    if (data.id) {
      this.setState({edit: true})
    }
    data.phone = e
    this.setState({data})
  }

  changeAddress(e) {
    const {data} = this.state
    if (data.id) {
      this.setState({edit: true})
    }
    data.address = e
    this.setState({data})
  }

  addChange(e) {
    const {data} = this.state
    if (data.id) {
      this.setState({edit: true})
    }
    data.addcode = e.detail.code
    data.addary = e.detail.value
    data.add = data.addary.join(",")
    this.setState({data})
  }

  async saveAdd() {
    const {data, api} = this.state
    if (!data.name) {
      Taro.showToast({
        title: '请输入收货人姓名',
        icon: 'none'
      })
      return false;
    }
    if (!(/^1\d{10}$/.test(data.phone))) {
      Taro.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      })
      return false;
    }
    if (!data.address) {
      Taro.showToast({
        title: '请填写详细地址',
        icon: 'none'
      })
      return false;
    }
    data.default = Number(data.default)
    const ret = await http.postCondition(api, data)
    if (ret) {
      Taro.showToast({
        title: '保存成功',
        icon: 'success',
        duration: 200,
        success: (res) => {
          Taro.navigateBack({
            delta: 1
          })
        }
      })

    }
  }

  showMenu() {
    this.setState({showNav: !this.state.showNav})
  }

  back() {
    const {data, edit} = this.state
    if (data.id && edit) {
      const that = this
      Taro.showModal({
        title: '提示',
        content: '是否保存本次编辑结果？',
        cancelText: '不保存',
        confirmText: '保存',
        success: function (res) {
          if (res.confirm) {
            that.saveAdd()
          } else if (res.cancel) {
            Taro.navigateBack({
              delta: 1
            })
          }
        }
      })

    } else {
      Taro.navigateBack({
        delta: 1
      })
    }
  }

  handleCityDataStr = key => {
    const add = key.split(",")
    const {formData} = this.state
    formData.province = add[0]
    formData.city = add[1]
    formData.country = add[2]
    this.setState({
      formData
    })
  }
  handleCityData = key => {
    const {addressData} = this.state
    // 处理数据。
    const provinceList = []; // 省
    const cityList = []; // 市
    const areaList = []; // 区
    for (let i = 0; i < addressData.length; i++) {
      // 获取省
      const province = addressData[i];
      provinceList.push(province.name);
    }
    if (addressData[key[0]].areaList && addressData[key[0]].areaList.length > 0) {
      for (let i = 0; i < addressData[key[0]].areaList.length; i++) {
        // 获取对应省下面的市
        const city = addressData[key[0]].areaList[i];
        cityList.push(city.name);
      }
    }
    for (
      let i = 0;
      i < addressData[key[0]].areaList[key[1]].areaList.length;
      i++
    ) {
      // 获取市下面对应区
      const country = addressData[key[0]].areaList[key[1]].areaList[i].name;
      areaList.push(country);
    }
    // }
    const newRange = [];
    newRange.push(provinceList);
    newRange.push(cityList);
    newRange.push(areaList);
    this.setState({
      rangeData: newRange, // 省市区所有的数据
      rangeKey: key // key是多列选择器需要展示的下标，因为是初始化，所以我们传入[0,0,0]
    });
  };
  getRangeKey = data => {
    const {addressData} = this.state
    // 详情的时候获取对应的展示位置
    const splitData = data.addressDescription.split("|");

    const getAddress = {
      province: splitData[0],
      city: splitData[1],
      country: splitData[2]
    };
    this.setState({
      formData: getAddress
    });
    let provinceIndex = 0;
    let cityIndex = 0;
    let countryIndex = 0;
    for (let i = 0; i < addressData.length; i++) {
      const province = addressData[i];
      if (province.name === getAddress.province) {
        provinceIndex = i;
        for (let j = 0; j < province.areaList.length; j++) {
          const city = province.areaList[j];
          if (city.name === getAddress.city) {
            cityIndex = j;
            for (let k = 0; k < city.areaList.length; k++) {
              const country = city.areaList[k].name;
              if (country === getAddress.country) {
                countryIndex = k;
                break;
              }
            }
            break;
          }
        }
        break;
      }
    }
    const rangeKey = [];
    rangeKey.push(provinceIndex);
    rangeKey.push(cityIndex);
    rangeKey.push(countryIndex);
    this.handleCityData(rangeKey);
  };
  onChange = e => {
    const {value} = e.detail;
    this.getAddressName(value);
  };
  getAddressName = value => {
    const {addressData} = this.state
    // 这里是转化用户选择的地址数据
    const {data} = this.state
    const formData = {
      province: "",
      city: "",
      country: ""
    };

    if (addressData[value[0]]) {
      formData.province = addressData[value[0]].name; // 省名称
      if (
        addressData[value[0]].areaList &&
        addressData[value[0]].areaList[value[1]]
      ) {
        formData.city = addressData[value[0]].areaList[value[1]].name;
        if (
          addressData[value[0]].areaList[value[1]].areaList &&
          addressData[value[0]].areaList[value[1]].areaList[value[2]]
        ) {
          formData.country =
            addressData[value[0]].areaList[value[1]].areaList[
              value[2]
              ].name;
        }
      }
    }
    //console.log(value)
    data.addary = value
    data.add = formData.province + ',' + formData.city + "," + formData.country
    this.setState({
      formData, data
    });
  };
  onColumnChange = e => {
    const {rangeKey} = this.state;
    const changeColumn = e.detail;
    const {column, value} = changeColumn;
    switch (column) { // 根据改变不同的列，来显示不同的数据
      case 0:
        this.handleCityData([value, 0, 0]);
        break;
      case 1:
        this.handleCityData([rangeKey[0], value, 0]);
        break;
      case 2:
        this.handleCityData([rangeKey[0], rangeKey[1], value]);
        break;
    }
  };

  render() {
    const {data, title, searchBarTop, showNav, listnum, delshow, rangeKey, rangeData, formData} = this.state;
    const headTop = getHeadTop()
    return (
      <View className='add-detail-root'>
        <GzhAuth />
        {/*{TARO_ENV !== 'h5' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>*/}
        {/*  <View className='header-car'*/}
        {/*    style={`padding-top: ${(headTop && (headTop.statusBar + headTop.top)) || 0}px;background-color:#fff`}*/}
        {/*  >*/}
        {/*    <View className='box-car'>*/}
        {/*      <View className='left' style='color:#000'>*/}
        {/*        <View className='back' onClick={this.back.bind(this)}><AtIcon value='chevron-left' size='18'*/}
        {/*          color='#000'*/}
        {/*        /></View>*/}
        {/*        <View className='menu' onClick={this.showMenu.bind(this)}><AtIcon prefixClass='at-icon' value='menu'*/}
        {/*          size='18'*/}
        {/*          color='#000'*/}
        {/*        /></View>*/}
        {/*      </View>*/}
        {/*      {showNav && <View className='nav' onClick={this.showMenu.bind(this)}>*/}
        {/*        <Navigator className='nav-li' url='/pages/index/index' openType='switchTab' hoverClass='none'><AtIcon*/}
        {/*          className='icon' prefixClass='xxhz' value='shouye1' size='16' color='black'*/}
        {/*        />首页</Navigator>*/}
        {/*        <Navigator className='nav-li' url='/common/search/search' hoverClass='none'><AtIcon className='icon'*/}
        {/*          prefixClass='xxhz'*/}
        {/*          value='sousuo'*/}
        {/*          size='16'*/}
        {/*          color='black'*/}
        {/*        />搜全站</Navigator>*/}
        {/*        <Navigator className='nav-li' url='/main/shopcar/index' hoverClass='none'><AtIcon className='icon'*/}
        {/*          prefixClass='xxhz'*/}
        {/*          value='gouwuche'*/}
        {/*          size='16'*/}
        {/*          color='black'*/}
        {/*        />购物车</Navigator>*/}
        {/*        <Navigator className='nav-li' url='/pages/my/index/index' openType='switchTab' hoverClass='none'><AtIcon*/}
        {/*          className='icon' prefixClass='xxhz' value='wode1' size='16' color='black'*/}
        {/*        />个人中心</Navigator>*/}
        {/*        <Navigator className='nav-li' url='/distributor/contact/contact' hoverClass='none'><AtIcon*/}
        {/*          className='icon' prefixClass='xxhz' value='icon-test7' size='16'*/}
        {/*          color='black'*/}
        {/*        />联系客服</Navigator>*/}
        {/*      </View>}*/}
        {/*      <View className='title' style='color: #fff;'>{title}</View>*/}
        {/*    </View>*/}
        {/*  </View>*/}
        {/*</View>}*/}
        <View className='edit-box'>
          <View className='form-group name'>
            <AtInput
              clear
              border={false}
              title='收货人'
              placeholder='姓名'
              type='text'
              value={data.name}
              onChange={this.changeName.bind(this)}
            />
          </View>
          <View className='form-group phone'>
            <AtInput
              clear
              border={false}
              title='联系方式'
              placeholder='手机号'
              type='phone'
              value={data.phone}
              onChange={this.changePhone.bind(this)}
            />
          </View>
          <View className='form-group add'>
            {process.env.TARO_ENV === "h5" ?
              <Picker
                mode='multiSelector' // 多列选择
                onChange={this.onChange} // change事件
                onColumnChange={this.onColumnChange} // 某列改变的事件
                range={rangeData} //需要展示的数据
                value={rangeKey} // 选择的下标
              >
                <View className='add-flex'>
                  <View className='label'>所在地区</View>
                  <View className='addcheck'>
                    {formData.province && (
                      <Text>
                        {formData.province}
                        {formData.city}
                        {formData.country}
                      </Text>
                    )}
                    {!formData.province && (
                      <Text style='color:#666'>选择省市区</Text>
                    )}
                    <AtIcon value='chevron-right' customStyle='font-size: 14px' size='14' color='#888888' />
                  </View>
                </View>
              </Picker>
              :
              <Picker mode='region' onChange={this.addChange.bind(this)} value={data.addcode ? data.addcode : []}>
                <View className='add-flex'>
                  <View className='label'>所在地区</View>
                  <View className='addcheck'>
                    {data.add
                      ?
                      <Text>{data.add.replace(/,/g, "")}</Text>
                      :
                      <Text style='color:#666'>选择省市区</Text>
                    }
                    <AtIcon value='chevron-right' customStyle='font-size: 14px' size='14' color='#888888' /></View>
                </View>
              </Picker>
            }

          </View>
          <View className='form-group address'>
            <AtInput
              clear
              border={false}
              title='详细地址'
              placeholder='详细地址需要填写楼栋楼层或房间号信息'
              type='text'
              value={data.address}
              onChange={this.changeAddress.bind(this)}
            />
          </View>
          <View className='form-group default'>
            <AtSwitch title='设为默认地址' checked={data.default} color={`${process.env.mainColor}`}
              onChange={this.handleChange.bind(this)}
            />
          </View>
        </View>
        <View className='save-add-btn' onClick={this.saveAdd.bind(this)}>保存地址</View>
        {listnum > 1 && <View className='del-add-btn' onClick={this.delShow.bind(this)}>删除地址</View>}
        {delshow && <View className='del-box'>
          <View className='del-bj' onClick={this.delShow.bind(this)} />
          <View className='del-main'>
            <View className='del-title'>确认删除该地址吗？</View>
            <View className='del-btn-box'>
              <View className='del-no' onClick={this.delShow.bind(this)}>取消</View>
              <View className='del-ok' onClick={this.delAdd.bind(this)}>确定</View>
            </View>
          </View>
        </View>}
      </View>
    );
  }
}

export default DetailWeb as ComponentClass<PageOwnProps, PageState>;
